package com.mall.shop.valid;

import com.mall.shop.annotation.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private int[] values;

    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] value = constraintAnnotation.value();
        if (Objects.nonNull(value) && value.length > 0) {
            values = value;
        } else {
            values = null;
        }
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        if (Objects.nonNull(values)) {
            for (int value : values) {
                if (integer == value) {
                    return true;
                }
            }
        }
        return false;
    }
}
